import { login } from '@/server/axios'
// 使用Cookie保存数据
import VueCookie from 'vue-cookie'
export default {
  state: {
    nickname: '',
    email: '',
    id: ''
  },
  mutations: {
    // 登录成功，获取用户信息
    loginSuccess (state, data) {
      const user = data.data
      state.nickname = user.nickname
      state.email = user.email
      state.id = user.id
    }
  },
  actions: {
    login ({ dispatch, commit }, data) {
      const { username, password } = data
      return new Promise((resolve, reject) => {
        login(data).then((res) => {
          if (res.status === 200) {
            const {token, ...userInfo} = res.data
            VueCookie.set('token', token.access_token, { expires: '1h' })
            commit({
              type: 'loginSuccess',
              data: userInfo
            })
            resolve()
          }
        }).catch(({ response }) => {
          console.log('error', response)
          const {data} = response
          console.log('data', data)
          // 如果登录失败，报异常
          reject(data)
        })
      })
    }
  }
}
